import { _decorator, Component, Node, Label, Prefab, instantiate, Widget, UITransform, isValid } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ScoreUI')
export class ScoreUI extends Component {
    @property([Prefab]) 
    scorePrefabList: Prefab[] = [];
    scoreNodeList:Node[]=[];

    protected onDestroy(): void {
        if(this.scoreNodeList.length > 0)
        {
            this.node.removeAllChildren();
            for (let index = 0; index < this.scoreNodeList.length; index++) {
                const element = this.scoreNodeList[index];
                if(element && isValid(element))
                {
                    element.destroy();
                }
            }
            this.scoreNodeList = [];
        }
    }

    updateUI(count:number)
    {
        this.onDestroy();

        let scoreString = count.toString();
        const LevelChars = Array.from(scoreString, Number); // 分割为单个字符

        const parentTransform = this.node.getComponent(UITransform);
        const parentWidth = parentTransform.width;
        let lastPosX = -parentWidth / 2 + 32; // 左对齐起始位置

        for (let index = 0; index < LevelChars.length; index++) {
            const char = LevelChars[index];
            const imageNode = this.scorePrefabList[char];
            
            if (!imageNode) {
                console.error(`Prefab for digit ${char} is missing`);
                continue;
            }
    
            const ScoreImg = instantiate(imageNode);
    
            // 设置初始属性
            const Transform = ScoreImg.getComponent(UITransform);
            Transform.width = 45;
            Transform.height = 53;
            
            if(index <= 0)
            {
                // 添加 Widget 并立即刷新
                const nodeWidget = ScoreImg.addComponent(Widget);
                nodeWidget.isAlignLeft = true;
                nodeWidget.left = 10;
            }
            else
            {
                // 计算位置
                const posX = lastPosX + 45;
                ScoreImg.setPosition(posX, 0, 0);
                lastPosX = ScoreImg.position.x;
            }
            
            
            this.node.addChild(ScoreImg);
            this.scoreNodeList.push(ScoreImg);
        }
    }
}


